package com.maserb.monitor.dataCenter.handler;

import com.maserb.monitor.dataCenter.communication.EigenWarningStatusEnum;
import com.maserb.monitor.entity.AlarmEntity;
import com.maserb.monitor.entity.EigenValueEntity;
import com.maserb.monitor.repository.AlarmRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Component
public class AlarmRepositoryHandler {

    @Autowired
    private AlarmRepository alarmRepository;

    public void publish(EigenValueEntity entity, List<EigenWarningStatusEnum> statuses, String deviceCode) {
        EigenWarningStatusEnum maxStatus = Collections.max(statuses, new Comparator<EigenWarningStatusEnum>() {
            @Override
            public int compare(EigenWarningStatusEnum o1, EigenWarningStatusEnum o2) {
                if (o1 == null) {
                    return -1;
                }
                if (o2 == null) {
                    return 1;
                }

                return o1.compareTo(o2);
            }
        });
        if (maxStatus != null && maxStatus.getValue() > EigenWarningStatusEnum.NORMAL.getValue()) {
            AlarmEntity alarmEntity = new AlarmEntity();
            alarmEntity.setDeviceCode(entity.getDeviceCode());
            alarmEntity.setPointCode(entity.getPointCode());
            alarmEntity.setStatus(maxStatus);

            alarmRepository.save(alarmEntity, deviceCode);
        }
    }
}
